#include"chatAImodel.hpp"
#include<muduo/base/Logging.h>
#include<stdio.h>


static size_t WriteCallback(void* contents, size_t size, size_t nmemb, std::string* buffer)
{
    size_t total_size = size * nmemb;
    buffer->append((char*)contents, total_size);
    return total_size;
}

ChatAIModel::ChatAIModel()
{
    curl_global_init(CURL_GLOBAL_DEFAULT);
    
    

    headers = curl_slist_append(headers, "Content-Type: application/json");

    FILE* pf = fopen("../config/api.conf","r");
    if (pf == nullptr)
	{
		LOG_ERROR<<"mysql loadConfigFile error: ";
	}

	while (!feof(pf))
	{
		char line[1024] = { 0 };
		// 先读一行
		fgets(line, 1024, pf);
		string str = line;
		int idx = str.find('=', 0);
		if (idx == -1) continue;

		int edx = str.find('\n', idx);
		string key = str.substr(0, idx);
		string value = str.substr(idx + 1, edx - idx - 1);

		if (key == "api")
		{
			api_key = value;
		}
		
	}
    fclose(pf);

    headers = curl_slist_append(headers, ("Authorization: Bearer " + api_key).c_str());

    
    

    request_body["model"] = "deepseek-chat";
    request_body["temperature"] = 1;
    request_body["max_tokens"] = 2048;


    
}

ChatAIModel::~ChatAIModel()
{
    curl_slist_free_all(headers);
    curl_global_cleanup();
}


// 聊天接口，传入用户请求数据，返回AI生成响应
string ChatAIModel::chat(json &historyMsg)
{
    // curl连接手柄
    CURL* curl;
    curl = curl_easy_init();

    // 设置API端点
    curl_easy_setopt(curl, CURLOPT_URL, "https://api.deepseek.com/chat/completions");
    curl_easy_setopt(curl, CURLOPT_HTTPHEADER, headers);


    
    
    request_body["messages"] = historyMsg["data"];

    

    string postdata = request_body.dump();

    

    // 设置post参数
    curl_easy_setopt(curl,CURLOPT_POSTFIELDS,postdata.c_str());
    curl_easy_setopt(curl,CURLOPT_POSTFIELDSIZE,postdata.size());

    // 设置相应回调
    string responsebuffer;
    curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, WriteCallback);
    curl_easy_setopt(curl, CURLOPT_WRITEDATA, &responsebuffer);

    // 请求执行
    res = curl_easy_perform(curl);

    // 相应数据
    if(CURLE_OK != res)
    {
        LOG_ERROR<<"ChatAI::chat: "<<"CURLE_OK != res 请求失败";
    }
    else
    {
        
        
        json response = json::parse(responsebuffer);

        if (response.contains("choices") && !response["choices"].empty()) 
        {
            string res = response["choices"][0]["message"]["content"].get<string>();
            curl_easy_cleanup(curl);
            return res;
        }
        else
        {   
            LOG_ERROR<<"ChatAI::chat: "<<" response error 错误响应";      
        }
    }

    curl_easy_cleanup(curl);
    return "服务器 AI 发生错误，请稍后再试";
}





